//
//  ProductListViewController.m
//  Tiger
//
//  Created by King on 11-10-10.
//  Copyright 2011 __MyCompanyName__. All rights reserved.
//

#import "ProductListViewController.h"
#import "ProductDetailViewController.h"
#import "ProductList.h"
#import "ProductListViewCell.h"
#import "TigerViewController.h"
#import "ProductSeriesDetailViewController.h"

#define kCustomRowCount     5

#define kProductID			@"productID"
#define kProductName		@"productName"
#define kProductNameEn		@"productNameEn"
#define kProductUrl			@"picUrl"
#define kProductCateID		@"cateID"
#define kProductCateName	@"cateName"


#define TagCH_CNName 0x200
#define TagEN_Name 0x201

#define DownTagCH_CNName 0x202
#define DownTagEN_Name 0x203
//int currentRow;

@implementation ProductListViewController

@synthesize cateID;
@synthesize tableView = tableView_;

@synthesize parsedDataArray;
@synthesize prolt;
@synthesize m_headimage;
@synthesize m_haedbutton;
@synthesize m_ListDataDic;

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil{
    if (self =[super initWithNibName:nibNameOrNil bundle:nibBundleOrNil]) {
        
    }
    return self;
}

// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad {
	
    [super viewDidLoad];
	self.parsedDataArray = [NSMutableArray arrayWithCapacity:50];
    p_AsiImages = [[NSMutableArray alloc] init];
    p_LastShowImgIndex = 0;
	[self sendRequestPayInfo];
	[self haedview];
    tableView_.separatorColor = [UIColor clearColor];
//	[self.tableView selectRowAtIndexPath:[NSIndexPath indexPathForRow:1 inSection:0]
//								animated:YES
//						  scrollPosition:UITableViewScrollPositionBottom];
//    p_TableViewBG =[[UIView alloc] initWithFrame:CGRectMake(0, 244, 320, 200)];
//    p_TableViewBG = []
//    CAGradientLayer* tBGGradlayer =[CAGradientLayer layer];
//    tBGGradlayer.colors = [NSArray arrayWithObjects:(id)[UIColor colorWithRed:70/255.f green:70/255.f blue:70/255.f alpha:1.0f].CGColor,
//                           (id)[UIColor blackColor].CGColor ,nil];
//    tBGGradlayer.frame =CGRectMake(0, 0, 320, 200);
//    [p_TableViewBG.layer addSublayer:tBGGradlayer];
//    tableView_.separatorColor = [UIColor grayColor];
    
    
//    p_WhiteButton = [UIButton buttonWithType:UIButtonTypeCustom];
//    [p_WhiteButton addTarget:self action:@selector(PressedToDetail:) forControlEvents:UIControlEventTouchUpInside];
//    [p_WhiteButton retain];
//    p_WhiteButton.frame =CGRectMake(0, 128, 320, 70);
//    p_WhiteButton.backgroundColor =[UIColor clearColor];
//    p_WhiteButton.layer.shadowOffset =CGSizeMake(3, 3);
//    p_WhiteButton.layer.shadowColor =[UIColor grayColor].CGColor;
//    CAGradientLayer* tGradlayer =[CAGradientLayer layer];
//    tGradlayer.colors = [NSArray arrayWithObjects:(id)[UIColor whiteColor].CGColor,
//                         (id)[UIColor lightGrayColor].CGColor ,nil];
//    tGradlayer.frame =CGRectMake(0, 0, 320, 70);
//    
//    [p_WhiteButton.layer addSublayer:tGradlayer];
//    
//    UIImageView* tArrow = [[UIImageView alloc] initWithFrame:CGRectMake(296, 20, 14, 14)];
//    UIImage* tImg =[UIImage imageNamed:@"br_nextblack.png"];
//    [tArrow setImage:tImg];
//    [p_WhiteButton addSubview:tArrow];
//    [tArrow release];
//    UILabel* tCHLabel =[[UILabel alloc] initWithFrame:CGRectMake(26, 2, 220, 36)];
//    tCHLabel.backgroundColor =[UIColor clearColor];
//    tCHLabel.font = [UIFont boldSystemFontOfSize:16.f];
//    tCHLabel.tag =TagCH_CNName;
//    tCHLabel.numberOfLines =2;
//    [p_WhiteButton addSubview:tCHLabel];
//    [tCHLabel release];
//    
//    UILabel* tENLabel =[[UILabel alloc] initWithFrame:CGRectMake(26, 40, 260, 28)];
//    tENLabel.backgroundColor =[UIColor clearColor];
//    tENLabel.font = [UIFont systemFontOfSize:12.f];
//    [tENLabel setTextColor:[UIColor grayColor]];
//    tENLabel.tag =TagEN_Name;
//    tENLabel.numberOfLines =2;
//    [p_WhiteButton addSubview:tENLabel];
//    [tENLabel release];
//    
//    [self.view addSubview:p_WhiteButton];
    
    p_IsPushToVC = NO;
}
- (void)haedview
{
    m_haedview = [[UIView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, 108)];
    [m_haedview setBackgroundColor:[UIColor clearColor]];
    
    
    UIImageView* imageview = [[UIImageView alloc] initWithFrame:CGRectMake(10, 10, 90, 70)];
    [imageview setImage:m_headimage];
    [m_haedview addSubview:imageview];
    [imageview release];
    
    UILabel* tCHLabel =[[UILabel alloc] initWithFrame:CGRectMake(110, 10, 200, 18)];
    tCHLabel.backgroundColor =[UIColor clearColor];
    [tCHLabel setTextColor:[UIColor whiteColor]];
    tCHLabel.font = [UIFont boldSystemFontOfSize:16.f];
    tCHLabel.numberOfLines =1;
    tCHLabel.text = [m_ListDataDic objectForKey:@"name"];
    [m_haedview addSubview:tCHLabel];
    [tCHLabel release];
    UILabel* tCHLabel1 =[[UILabel alloc] initWithFrame:CGRectMake(110, 30, 200, 18)];
    tCHLabel1.backgroundColor =[UIColor clearColor];
    [tCHLabel1 setTextColor:[UIColor whiteColor]];
    tCHLabel1.font = [UIFont boldSystemFontOfSize:16.f];
    tCHLabel1.numberOfLines =1;
    tCHLabel1.text = [m_ListDataDic objectForKey:@"subname"];
    [m_haedview addSubview:tCHLabel1];
    [tCHLabel1 release];
    
    UILabel* tENLabel =[[UILabel alloc] initWithFrame:CGRectMake(110, 52, 200, 14)];
    tENLabel.backgroundColor =[UIColor clearColor];
    tENLabel.font = [UIFont systemFontOfSize:12.f];
    [tENLabel setTextColor:[UIColor grayColor]];
    tENLabel.text =[m_ListDataDic objectForKey:@"summeryOne"];
    tENLabel.numberOfLines =1;
    [m_haedview addSubview:tENLabel];
    [tENLabel release];
    UILabel* tENLabel1 =[[UILabel alloc] initWithFrame:CGRectMake(110, 68, 200, 14)];
    tENLabel1.backgroundColor =[UIColor clearColor];
    tENLabel1.font = [UIFont systemFontOfSize:12.f];
    [tENLabel1 setTextColor:[UIColor grayColor]];
    tENLabel1.text =[m_ListDataDic objectForKey:@"summeryTow"];
    tENLabel1.numberOfLines =1;
    [m_haedview addSubview:tENLabel1];
    [tENLabel1 release];
    
    self.m_haedbutton = [UIButton buttonWithType:UIButtonTypeCustom];
    [self.m_haedbutton setFrame:CGRectMake(220, 85, 50, 20)];
    [self.m_haedbutton setBackgroundImage:[UIImage imageNamed:@"button1"] forState:UIControlStateNormal];
    self.m_haedbutton.titleLabel.font = [UIFont systemFontOfSize:12.0f];
    [self.m_haedbutton setTitleColor:[UIColor grayColor] forState:UIControlStateNormal];
    [self.m_haedbutton setTitle:@"介 绍 >" forState:UIControlStateNormal];
    [self.m_haedbutton addTarget:self action:@selector(ProductSeriesbutton) forControlEvents:UIControlEventTouchUpInside];
    [m_haedview addSubview:self.m_haedbutton];
    [self.view addSubview:m_haedview];
  
}
- (void)ProductSeriesbutton
{
    ProductSeriesDetailViewController *viewController = [[ProductSeriesDetailViewController alloc] init];
    viewController.m_SerDicData = m_ListDataDic;
    viewController.m_cateID = cateID;
    viewController.m_psimage = self.m_headimage;
	UIBarButtonItem *backButton = [[UIBarButtonItem alloc]
								   initWithTitle:@"产品列表" 
								   style:UIBarButtonItemStylePlain 
								   target:self
								   action:nil];
	self.navigationItem.backBarButtonItem = backButton;
	//导航自带的动画
	[self.navigationController pushViewController:viewController animated:YES];
	[viewController release];
}
-(void) PressedToDetail:(NSInteger)sendertag{
    if (sendertag<[parsedDataArray count]) {
		//currentRow=indexPath.row;
		
//		[self.tableView selectRowAtIndexPath:[NSIndexPath indexPathForRow:sender.tag inSection:0]
//									animated:YES
//							  scrollPosition:UITableViewScrollPositionTop];
		
		
        
		prolt = [self.parsedDataArray objectAtIndex:sendertag];
        
        NSLog(@"321 =%@",prolt.productName);
        [self TimeCountDown];
//		NSTimer *pTime;
//		
//		pTime = [[NSTimer scheduledTimerWithTimeInterval:0.7
//												  target:self
//												selector:@selector(TimeCountDown:)
//												userInfo:nil
//												 repeats:NO] retain];
//		[pTime release];
        
	}
}

- (void)sendRequestPayInfo{	
	//GET 请求
	NSString *getURL = [NSString stringWithFormat:@"http://www.speedtiger.com.cn/ios3/product_list.html?cateID=%d", cateID];
    NSLog(@"url =%@",getURL);
	//NSLog(@"发送注册请求URL：%@", getURL);
	ASIHTTPRequest *request = [[ASIHTTPRequest alloc] initWithURL:[NSURL URLWithString:getURL]];
	request.tag = -1;
	[request setValidatesSecureCertificate:NO];
	[request setDelegate:self];
	[request startAsynchronous];
}


#pragma mark ASIHTTPRequestDelegate methods
- (void)requestStarted:(ASIHTTPRequest *)request
{
	[UIApplication sharedApplication].networkActivityIndicatorVisible = YES;
}


- (void)requestFinished:(ASIHTTPRequest *)request
{
	NSData *responseData = [request responseData];
	NSString *responseStr = [[[NSString alloc] initWithData:responseData encoding: NSUTF8StringEncoding] autorelease];
	if (request.tag < 0) 
	{
		NSDictionary *dict = [responseStr JSONValue];
		NSArray *dictList = [dict objectForKey:@"items"];
        [p_AsiImages removeAllObjects];
		NSLog(@"dictList = %d",[dictList count]);
		for (int i=0; i<[dictList count]; i++) {
			NSDictionary *dict = [dictList objectAtIndex:i];
			ProductList *prolist = [[ProductList alloc] init];
			prolist.productID = [dict objectForKey:kProductID];
			prolist.productName = [dict objectForKey:kProductName];
			prolist.productNameEn = [dict objectForKey:kProductNameEn];
			prolist.picUrl = [dict objectForKey:kProductUrl];
			prolist.cateID = [dict objectForKey:kProductCateID];
			prolist.cateName = [dict objectForKey:kProductCateName];
			[parsedDataArray addObject:prolist];
            
            AsyncImageView* tImgs =[[AsyncImageView alloc] initWithFrame:CGRectMake(8, 7, 50, 50)];
            tImgs._numStateRequested = need_Request;
            tImgs._imageRequestURL = prolist.picUrl;
            tImgs.m_BoolSetImage = YES;
            [p_AsiImages addObject:tImgs];
//            if (i==0) {
                [tImgs customLoadImageFromURL];
//               [self.view addSubview:tImgs];
//            }
            [tImgs release];
            [prolist release];
            
		}
//        if ([parsedDataArray count] > 0) {
//            ProductList*  tProlt = [parsedDataArray objectAtIndex:0];
            
//            UILabel* chLabel =(UILabel*)[p_WhiteButton viewWithTag:TagCH_CNName];
//            chLabel.text = tProlt.productName;
//            UILabel* enLabel =(UILabel*)[p_WhiteButton viewWithTag:TagEN_Name];
//            enLabel.text = tProlt.productNameEn;
//            UILabel* chLabel =(UILabel*)[m_haedview viewWithTag:TagCH_CNName];
//            chLabel.text = tProlt.productName;
//            UILabel* enLabel =(UILabel*)[m_haedview viewWithTag:TagEN_Name];
//            enLabel.text = tProlt.productNameEn;
            
//        }
        
		[self.tableView reloadData];
	}
	else {
		NSLog(@"recved bad data !");
	}
}

- (void)requestFailed:(ASIHTTPRequest *)request
{
	[UIApplication sharedApplication].networkActivityIndicatorVisible = NO;

	UIAlertView *alert = [[[UIAlertView alloc] initWithTitle:@"温馨提示" message:@"无可用的网络连接" delegate:self 
										   cancelButtonTitle:nil otherButtonTitles:nil] autorelease];
	[alert addButtonWithTitle:@"确定"];
	[alert show];
	
}


#pragma mark Table view methods
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
	return 65.0;
}

// Customize the number of rows in the table view.
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section 
{
	int count = [parsedDataArray count];
    if (count == 0)
	{
        return kCustomRowCount;
    }
    return count;
	
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath 
{
   // [tableView setBackgroundView:p_TableViewBG];
	static NSString* CellIdentifier = @"Cellidentifier";
	static NSString *PlaceholderCellIdentifier = @"PlaceholderCell";	
	int nodeCount = [self.parsedDataArray count];
	//NSLog(@"nodeCount = %d", nodeCount);
	if (nodeCount == 0 && indexPath.row == 0)
	{
        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:PlaceholderCellIdentifier];
        if (cell == nil)
		{
            cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle
										   reuseIdentifier:PlaceholderCellIdentifier] autorelease];   
            cell.detailTextLabel.textAlignment = UITextAlignmentCenter;
			cell.selectionStyle = UITableViewCellSelectionStyleNone;
        }
        
		cell.detailTextLabel.text = @"数据加载中，请稍后…";
		
		return cell;
    }

	ProductListViewCell *cell = (ProductListViewCell *) [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [[[ProductListViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle 
									   reuseIdentifier:CellIdentifier] autorelease];
		UIImageView* tCustomImgView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 14, 14)];
        [tCustomImgView setImage:[UIImage imageNamed:@"br_nextwhite.png"]];
        cell.accessoryView = tCustomImgView;
        [tCustomImgView release];
    }
	if (nodeCount > 0)
	{
		ProductList* tCellprolt = [self.parsedDataArray objectAtIndex:indexPath.row];
		
		//NSURL *url=[NSURL URLWithString:prolt.picUrl];
		//[myImageView setImageWithURL:url];

        if ([p_AsiImages count]>0) {
//           AsyncImageView* asyncimage  = (AsyncImageView*)[p_AsiImages objectAtIndex:indexPath.row];
//            [cell.contentView addSubview:asyncimage];
        }
		cell.productName = tCellprolt.productName;
		
		cell.selectionStyle = UITableViewCellSelectionStyleNone;
	}
	
	return cell;
}


- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    [self PressedToDetail:indexPath.row];
//    if (p_IsPushToVC) {
//        return;
//    }
//    if (indexPath.row == p_LastShowImgIndex) {
//        CGPoint aOffset =CGPointMake(0,55*(indexPath.row+1));
//        
//        [UIView beginAnimations:nil context:nil];
//        [UIView setAnimationCurve:UIViewAnimationCurveEaseInOut];
//        [UIView setAnimationDelegate:self];
//        [UIView setAnimationDidStopSelector:@selector(removeLastView)];
//        [UIView setAnimationDuration:0.5f];
//        tableView.contentOffset =aOffset;
//        [UIView commitAnimations];
//        return;
//    }
//    p_IsPushToVC =YES;
//    CGPoint aOffset =CGPointMake(0,55*(indexPath.row+1));
////    [tableView scrollToRowAtIndexPath:indexPath atScrollPosition:UITableViewScrollPositionTop animated:YES];
//    p_WhiteButton.clipsToBounds =YES;
//    UILabel* tDownCHLabel =[[UILabel alloc] initWithFrame:CGRectMake(26, 72, 220, 36)];
//    tDownCHLabel.backgroundColor =[UIColor clearColor];
//    tDownCHLabel.font = [UIFont boldSystemFontOfSize:16.f];
//    tDownCHLabel.tag =DownTagCH_CNName;
//    tDownCHLabel.numberOfLines =2;
//    [p_WhiteButton addSubview:tDownCHLabel];
//    [tDownCHLabel release];
//    
//    UILabel* tDownENLabel =[[UILabel alloc] initWithFrame:CGRectMake(26, 110, 260, 28)];
//    tDownENLabel.backgroundColor =[UIColor clearColor];
//    tDownENLabel.font = [UIFont systemFontOfSize:12.f];
//    [tDownENLabel setTextColor:[UIColor grayColor]];
//    tDownENLabel.tag =DownTagEN_Name;
//    tDownENLabel.numberOfLines =2;
//    [p_WhiteButton addSubview:tDownENLabel];
//    
//    ProductList* newprolt = [self.parsedDataArray objectAtIndex:indexPath.row];
//    p_WhiteButton.tag = indexPath.row;
//    UILabel* chLabel =(UILabel*)[p_WhiteButton viewWithTag:TagCH_CNName];
//    tDownCHLabel.text = newprolt.productName;
//    UILabel* enLabel =(UILabel*)[p_WhiteButton viewWithTag:TagEN_Name];
//    tDownENLabel.text = newprolt.productNameEn;
//    
////    AsyncImageView* tShow =[p_AsiImages objectAtIndex:indexPath.row];
////    if (tShow._numStateRequested == need_Request) {
////        [tShow customLoadImageFromURL];
////    }
////    tShow.frame =CGRectMake(0, 234, 320, 60);
////    [self.view insertSubview:tShow atIndex:2];
//    AsyncImageView* tLastShow =[p_AsiImages objectAtIndex:p_LastShowImgIndex];
//    p_NowShowIndex = indexPath.row;
//    
//    
//    [UIView beginAnimations:nil context:nil];
//    [UIView setAnimationCurve:UIViewAnimationCurveEaseInOut];
//    [UIView setAnimationDuration:0.5f];
//    [UIView setAnimationDelegate:self];
//    [UIView setAnimationDidStopSelector:@selector(removeLastView)];
////    tShow.frame =CGRectMake(0, 34, 320, 60);
//    tLastShow.frame =CGRectMake(0,-166, 320, 60);
//    chLabel.frame =CGRectMake(26, -68, 220, 36);
//    enLabel.frame =CGRectMake(26, -30, 260, 28);
//    tDownCHLabel.frame =CGRectMake(26, 2, 220, 36);
//    tDownENLabel.frame =CGRectMake(26, 40, 260, 28);
//    tableView.contentOffset =aOffset;
//    [UIView commitAnimations];
    
    
	//[self.tableView reloadData];
	
}

-(void)removeLastView{
    AsyncImageView* tLastShow =[p_AsiImages objectAtIndex:p_LastShowImgIndex];
    tLastShow.frame = CGRectMake(0, 34, 320, 60);
    [tLastShow removeFromSuperview];
    p_LastShowImgIndex =p_NowShowIndex;
    p_NowShowIndex = 0;
    
    
    UILabel* chLabel =(UILabel*)[p_WhiteButton viewWithTag:TagCH_CNName];
    [chLabel removeFromSuperview];
    UILabel* enLabel =(UILabel*)[p_WhiteButton viewWithTag:TagEN_Name];
    [enLabel removeFromSuperview];
    
    UILabel* cdhLabel =(UILabel*)[p_WhiteButton viewWithTag:DownTagCH_CNName];
    cdhLabel.tag =TagCH_CNName;
    UILabel* endLabel =(UILabel*)[p_WhiteButton viewWithTag:DownTagEN_Name];
    endLabel.tag =TagEN_Name;
    [self PressedToDetail:p_LastShowImgIndex];
}


- (void)TimeCountDown
{
	ProductDetailViewController *viewController = [[ProductDetailViewController alloc] initWithNibName:@"ProductDetailViewController" bundle:nil];
	viewController.hidesBottomBarWhenPushed = YES;
    NSLog(@"%@",prolt.productName);
	viewController.productID = [prolt.productID intValue];
	//导航自带的动画
	UIBarButtonItem *backButton = [[UIBarButtonItem alloc]
								   initWithTitle:@"产品列表" 
								   style:UIBarButtonItemStylePlain 
								   target:self
								   action:nil];
	self.navigationItem.backBarButtonItem = backButton;
	[self.navigationController pushViewController:viewController animated:YES];
	[viewController release];
    
    p_IsPushToVC =NO;
}


- (void)didReceiveMemoryWarning {
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    
    // Release any cached data, images, etc. that aren't in use.
}

- (void)viewDidUnload {
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;

	//self.myImageView = nil;
}


- (void)dealloc {
    [tableView_ release];
	[parsedDataArray release];
    [p_AsiImages release];
    [p_WhiteButton release];
    [p_TableViewBG release];
    [m_haedview release];
     [m_headimage release];
     m_haedbutton = nil;
    [super dealloc];



	
}


@end
